using Godot;
using Godot.Collections;
using System;
using System.IO;

public partial class CEquipment : Node
{
	[Signal]
	public delegate void EquipItemChangedEventHandler(Item item);
	[Export]
	public int item_count;
	[Export]
	public Dictionary<string,Item> items = new Dictionary<string, Item>();
	private UiInventory _inventory;
	private GridContainer _equipItemGrid;
	private Player _player;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	
	public void add_item(string to ,Item item)
	{
		items[to] = item;
		(_player.CharacterData as PlayerData).Equipment[to] = item.name;
		if(item != null)
		{GD.Print((_player.CharacterData as PlayerData).Equipment[to]);}
		EmitSignal(SignalName.EquipItemChanged, item);
	}
	public void remove_item(string from,Item item)
	{
		string path;
		if(from == "itemslot")
		{ path = FindKeyByValue(item);}
		else
		{
			 path = from;
		}
		items[path] = null;
		(_player.CharacterData as PlayerData).Equipment[path] = item.name;

		EmitSignal(SignalName.EquipItemChanged, item);
	}

	public string get_empty_slot_index()
	{
		
		return null;
	}

	public void Initialize()
	{
		_player = Owner as Player;
		var UIControl = GetNode<UIControl>("/root/UIControl");
		_inventory = UIControl.GetGuiViewManager().GetNode<UiInventory>("%UiInventory");
		_equipItemGrid = _inventory.GetNode<GridContainer>("%EquipGrid");

		var item = (_player.CharacterData as PlayerData).Equipment;
		foreach (string key in item.Keys)
		{
			if(item[key] == null||item[key] =="")
			{continue;}
			var Game = GetNode<Game>("/root/Game");
			Item value = Game.LoadItem(item[key]);
			add_item(key,value);
		}

		var children = _equipItemGrid.GetChildren();
		
		foreach (var slot in children )
		{
			items[slot.Name] = null;
		}
	}
	public string FindKeyByValue(Item item)
	{
		foreach (string Key in items.Keys)
		{
			if(items[Key] == item)
			{
				return Key;
			}
			
		}
		return null;
	}
}
